package com.ybkj.daijia.api.apirest.v4;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.OrderConfirmLocs;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.errand.Order;
import com.ybkj.daijia.server.errand.OrderType;
import com.ybkj.daijia.server.errand.OrderUp;
import com.ybkj.daijia.server.errand.OrderUp.PayTypeDetails;
import com.ybkj.daijia.server.event.model.OrderEmployHasPayEvent;
import com.ybkj.daijia.server.event.model.OrderPassengerHasPayEvent;
import com.ybkj.daijia.server.event.model.errand.ErrandOrderUpCancelEvent;
import com.ybkj.daijia.server.event.model.errand.ErrandOrderUpConfirmEvent;
import com.ybkj.daijia.server.event.model.errand.ErrandOrderUpRunEvent;
import com.ybkj.daijia.server.event.model.errand.PaotuiOrderUpAcceptEvent;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverRefuseRecord;
import com.ybkj.daijia.server.model.FirstOrderPassenger;
import com.ybkj.daijia.server.model.OrderLocation;
import com.ybkj.daijia.server.model.OrderLocationMany;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.DriverRefuseRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandUpService;
import com.ybkj.daijia.server.service.FirstOrderPassengerService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderLocationManyService;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;


@Controller("ApiErrandProcessUpControllerV4")
@RequestMapping(value = "api/errand/v4/up/")
public class ErrandProcessUpController {

    private static final Logger logger = LoggerFactory.getLogger(ErrandProcessUpController.class);

    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ErrandUpService errandService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverRefuseRecordService driverRefuseRecordService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private OrderLocationManyService orderLocationManyService;
    @Autowired
    private FirstOrderPassengerService firstOrderPassengerService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private DriverMapper driverMapper;

    /**
     * 完成任务调用接口
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "completeTaskData", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport completeTask(Long orderId) {

        logger.error("recv orderId:{}", orderId);

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        OrderUp order = errandService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        Driver driver = driverService.findOne(order.getEmployId());
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }
        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
        }

        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("orderId", order.getId());
            map.put("orderNumber", order.getOrderNo());
            map.put("orderType", "errand");
            map.put("passengerPhone", passenger.getPhone());
            map.put("passengerName", passenger.getName());
            map.put("passengerType", passenger.getTypeStr());

            //等级
            map.put("passengerGrade", passenger.getGrade_name());

            Company orderCompany = companyService.findOne(order.getCompanyId());
            map.put("orderCompanyName", orderCompany.getAbbreviation());

            Company passengerCompany = companyService.findOne(passenger.getCompanyId());
            map.put("passengerCompanyName", passengerCompany.getAbbreviation());

            if (passenger.getType() == Passenger.TYPE_PASSENGER) {
                map.put("overdraw", passenger.isAllowOverdraw());
                map.put("virtual", passenger.getDrawMoney().add(passenger.getNodrawMoney())
                    .setScale(2, BigDecimal.ROUND_HALF_UP));
            } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
                Enterprise enterprise = memberService
                    .findOneEnterprise(passenger.getEnterprise_id());
                map.put("overdraw", enterprise.isAllowOverdraw());
                map.put("virtual", enterprise.getDrawMoney().add(enterprise.getNodrawMoney())
                    .setScale(2, BigDecimal.ROUND_HALF_UP));
            }

            //优惠券
            if (null != order.getCouponId()) {
                Coupon coupon = couponService.findOne(order.getCouponId());
                if (null != coupon) {
                    CouponRule couponRule = coupon.getCouponRule();
                    if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                        map.put("couponMoney", couponRule.getMoney());
                        map.put("coupon_type", CouponRule.TYPE_DEDUCTION);
                    } else if (couponRule.getType().equals(CouponRule.TYPE_DISCOUNT)) {
                        map.put("discount", couponRule.getDiscount());
                        map.put("coupon_type", CouponRule.TYPE_DISCOUNT);
                    }
                }
            }

            //预先支付
            BigDecimal preyMoney = BigDecimal.ZERO;
            if (order.isIfPayed()) {
                preyMoney = preyMoney.add(new BigDecimal(order.getSignMoney()));
                preyMoney = preyMoney.add(new BigDecimal(order.getBalanceMoney()));
                preyMoney = preyMoney.add(new BigDecimal(order.getAlipayMoney()));
                preyMoney = preyMoney.add(new BigDecimal(order.getWeixinMoney()));
                preyMoney = preyMoney.add(new BigDecimal(order.getUnionpayMoney()));
            }
            map.put("preyMoney", preyMoney.setScale(2, BigDecimal.ROUND_HALF_UP));
            map.put("payed", order.isIfPayed());

            //首单免费
            Long completeTimes = firstOrderPassengerService
                .selectAll(passenger.getId(), FirstOrderPassenger.FREE_ORDERTYPE_ERRAND);
            if (completeTimes > 0) {
                map.put("firstFree", false);
            } else {
                map.put("firstFree", true);
            }

            map.put("employId", driver.getId());
            map.put("employName", driver.getName());
            map.put("employPhone", driver.getPhone());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(map);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "checkTask", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport checkTask(Long orderId) {

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        OrderUp order = errandService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {

            boolean finished = false;
            if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                finished = true;
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(finished);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "confirmTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport confirmTask(
        Long orderId, BigDecimal realCash, Double mileage, Integer waitedTime, Integer travelTime,
        BigDecimal guoluMoney, BigDecimal yuanchengMoney, BigDecimal otherMoney, BigDecimal czMoney,
        @RequestParam(required = false, value = "goodsCash") Double goodsCash,
        @RequestParam(required = false, value = "thanksCash") Double thanksCash,
        @RequestParam(required = false, value = "weightPrice") Double weightPrice,
        @RequestParam(required = false, value = "protectPrice") Double protectPrice,
        @RequestParam(required = false, value = "startPrice") BigDecimal startPrice,
        @RequestParam(required = false, value = "mileagePrice") BigDecimal mileagePrice,
        @RequestParam(required = false, value = "runTimePrice") BigDecimal runTimePrice,
        @RequestParam(required = false, value = "waitPrice") BigDecimal waitPrice,
        @RequestParam(required = false, value = "memo") String memo,
        @RequestParam(required = false, value = "pictures") String confirmPictures,
        HttpServletRequest req,
        @RequestParam(required = false, value = "jsonLocs") String jsonLocs) {

        return confirmTaskFunction(orderId, realCash, goodsCash, thanksCash, guoluMoney,
            yuanchengMoney, otherMoney, mileage, waitedTime, travelTime,
            startPrice, mileagePrice, runTimePrice, waitPrice, memo, null, null, jsonLocs, null,
            weightPrice, protectPrice, czMoney, confirmPictures);
    }

    @RequestMapping(value = "confirmTaskJsonFile", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport confirmTaskJsonFile(
        HttpServletRequest req,
        Long orderId, BigDecimal realCash, Double mileage, Integer waitedTime, Integer travelTime,
        BigDecimal guoluMoney, BigDecimal yuanchengMoney, BigDecimal otherMoney, BigDecimal czMoney,
        @RequestParam(required = false, value = "goodsCash") Double goodsCash,
        @RequestParam(required = false, value = "thanksCash") Double thanksCash,
        @RequestParam(required = false, value = "weightPrice") Double weightPrice,
        @RequestParam(required = false, value = "protectPrice") Double protectPrice,
        @RequestParam(required = false, value = "startPrice") BigDecimal startPrice,
        @RequestParam(required = false, value = "mileagePrice") BigDecimal mileagePrice,
        @RequestParam(required = false, value = "runTimePrice") BigDecimal runTimePrice,
        @RequestParam(required = false, value = "waitPrice") BigDecimal waitPrice,
        @RequestParam(required = false, value = "memo") String memo,
        @RequestParam(required = false, value = "justKilometres") Double justKilometres,
        @RequestParam(required = false, value = "justMoney") BigDecimal justMoney,
        @RequestParam(required = false, value = "jsonLocs") String jsonLocs,
        @RequestParam(required = false, value = "picture0") MultipartFile picture0,
        @RequestParam(required = false, value = "picture1") MultipartFile picture1,
        @RequestParam(required = false, value = "picture2") MultipartFile picture2,
        @RequestParam(required = false, value = "picture3") MultipartFile picture3,
        @RequestParam(required = false, value = "picture4") MultipartFile picture4,
        @RequestParam(required = false, value = "picture5") MultipartFile picture5,
        @RequestParam(required = false, value = "picture6") MultipartFile picture6,
        @RequestParam(required = false, value = "picture7") MultipartFile picture7,
        @RequestParam(required = false, value = "picture8") MultipartFile picture8,
        @RequestParam(required = false, value = "picture9") MultipartFile picture9,
        @RequestParam(required = false, value = "jsonLocFile") MultipartFile jsonLocFile) {
        String confirmPictures = "";
        if (null != picture0) {
            confirmPictures += getFileName(req, picture0) + ",";
        }
        if (null != picture1) {
            confirmPictures += getFileName(req, picture1) + ",";
        }
        if (null != picture2) {
            confirmPictures += getFileName(req, picture2) + ",";
        }
        if (null != picture3) {
            confirmPictures += getFileName(req, picture3) + ",";
        }
        if (null != picture4) {
            confirmPictures += getFileName(req, picture4) + ",";
        }
        if (null != picture5) {
            confirmPictures += getFileName(req, picture5) + ",";
        }
        if (null != picture6) {
            confirmPictures += getFileName(req, picture6) + ",";
        }
        if (null != picture7) {
            confirmPictures += getFileName(req, picture7) + ",";
        }
        if (null != picture8) {
            confirmPictures += getFileName(req, picture8) + ",";
        }
        if (null != picture9) {
            confirmPictures += getFileName(req, picture9) + ",";
        }
        return confirmTaskFunction(orderId, realCash, goodsCash, thanksCash, guoluMoney,
            yuanchengMoney, otherMoney, mileage, waitedTime, travelTime,
            startPrice, mileagePrice, runTimePrice, waitPrice, memo, justKilometres, justMoney,
            jsonLocs, jsonLocFile, weightPrice, protectPrice, czMoney, confirmPictures);
    }

    private String getFileName(HttpServletRequest req, MultipartFile file) {
        try {
            String bathPath = getBasePath(req);
            File dir = new File(bathPath, "upload/errand");
            FileUtils.forceMkdir(dir);
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = String
                .format("%s.png", df.format(new Date()) + "_" + new Random().nextInt(1000));
            File newFile = new File(dir, fileName);
            FileOutputStream out = new FileOutputStream(newFile);
            byte[] data = file.getBytes();
            IOUtils.write(data, out);
            Thumbnails.of(newFile).size(400, 400).toFile(newFile);
            IOUtils.closeQuietly(out);
            return "upload/errand/" + fileName;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return "";
    }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }

    private ResultTransport confirmTaskFunction(
        Long orderId, BigDecimal realCash,
        Double goodsCash, Double thanksCash,
        BigDecimal guoluMoney, BigDecimal yuanchengMoney, BigDecimal otherMoney,
        Double mileage, Integer waitedTime, Integer travelTime,
        BigDecimal startPrice, BigDecimal mileagePrice, BigDecimal runTimePrice,
        BigDecimal waitPrice, String memo, Double justKilometres, BigDecimal justMoney,
        String jsonLocs, MultipartFile jsonLocFile, Double weightPrice, Double protectPrice,
        BigDecimal czMoney, String confirmPictures) {
        logger.error(
            "recv orderId:{},realCash:{},guoluMoney:{},yuanchengMoney:{},otherMoney:{},startPrice:{},"
                + "mileagePrice:{},runTimePrice:{},waitPrice:{},mileage:{},waitedTime:{},travelTime:{},memo:{}",
            orderId, realCash, guoluMoney, yuanchengMoney, otherMoney, startPrice, mileagePrice,
            runTimePrice, waitPrice, mileage, waitedTime, travelTime, memo);
        if (null == orderId || null == realCash || null == mileage || null == waitedTime
            || null == travelTime) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        OrderUp order = errandService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (order.getTreatment()) {
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData("waitfinish");
            return instance;
        }

        if (!StringUtils.isBlank(confirmPictures)) {
            order.setConfirmPictures(confirmPictures.substring(0, confirmPictures.length() - 1));
        }
        try {
            order.setGuoluMoney(guoluMoney == null ? 0 : guoluMoney.doubleValue());
            order.setYuanchengMoney(yuanchengMoney == null ? 0 : yuanchengMoney.doubleValue());
            order.setOtherMoney(otherMoney == null ? 0 : otherMoney.doubleValue());
            order.setCzMoney(czMoney == null ? 0 : czMoney.doubleValue());
            //realCash是实际服务费+过路费+远程费+其他费用+调价
            order.setRealPay((realCash != null ? realCash.doubleValue() : 0));
            order.setGoodsCash(goodsCash != null ? goodsCash : 0);
            order.setThanksCash(thanksCash != null ? thanksCash : 0);
            order.setWeightPrice(weightPrice != null ? weightPrice : 0);
//            order.setProtectPrice(protectPrice!=null?protectPrice:0);
            //优惠券
            Coupon coupon = null;
            BigDecimal coupon_hasPayed = BigDecimal.ZERO;
            Double discount = null;
            if (null != order.getCouponId()) {
                coupon = couponService.findOne(order.getCouponId());
                if (null != coupon) {
                    if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
                        coupon_hasPayed = coupon.getCouponRule().getMoney();
                    } else if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DISCOUNT)) {
                        discount = coupon.getCouponRule().getDiscount();
                        coupon_hasPayed = realCash
                            .add(new BigDecimal(weightPrice != null ? weightPrice : 0))
                            .subtract(guoluMoney)
                            .multiply(new BigDecimal(1)
                                .subtract(new BigDecimal(discount).divide(new BigDecimal(10))))
                            .setScale(0, BigDecimal.ROUND_DOWN);
                    }
                }
            }
            if (realCash.add(new BigDecimal(weightPrice != null ? weightPrice : 0))
                .subtract(guoluMoney).subtract(coupon_hasPayed).doubleValue() > 0) {
                order.setCouponMoney(coupon_hasPayed.doubleValue());
            } else {
                order.setCouponMoney(
                    realCash.add(new BigDecimal(weightPrice != null ? weightPrice : 0))
                        .subtract(guoluMoney).doubleValue());
            }
            if (coupon_hasPayed.doubleValue() > 0 && null == order.getPrePayTypeDetail()) {
                order.setPrePayTypeDetail(PayTypeDetails.coupon);
            }
            order.setDiscount(discount);
            order.setTreatment(true);

            order.setStartPrice(startPrice.doubleValue());
            order.setMileagePrice(mileagePrice.doubleValue());
            order.setTravelTimePrice(runTimePrice.doubleValue());
            order.setTravelTime(travelTime);
            order.setMileage(
                new BigDecimal(mileage).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            order.setWaitedTime(waitedTime);
            order.setWaitPrice(waitPrice.doubleValue());
            if (null != justKilometres) {
                order.setJustKilometres(justKilometres);
            }
            if (null != justMoney) {
                order.setJustMoney(justMoney);
            }

            Result<OrderUp> result = errandService.confirmTask(order, null, memo);

            Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
            if (StringUtils.isNotBlank(memo)) {
                passenger.setPlateNumber(memo);
                memberService.updatePassenger(passenger);
            }

            if (result.isSuccess()) {
                //保存位置
                if (null != jsonLocFile) {
                    jsonLocs = OrderConfirmLocs.locs(jsonLocFile);
                }

                if (StringUtils.isNotBlank(jsonLocs)) {
                    OrderLocationMany orderLocationMany = new OrderLocationMany();
                    orderLocationMany.setOrderId(orderId);
                    orderLocationMany.setOrderType(OrderLocation.OrderType.errand);
                    orderLocationMany.setJsonLocs(jsonLocs);
                    orderLocationManyService.save(orderLocationMany);
                }
                BigDecimal hasPayed = BigDecimal.ZERO;//之前已经实际支付的钱
                if (order.isIfPayed()) {
                    hasPayed = hasPayed.add(new BigDecimal(order.getSignMoney()));
                    hasPayed = hasPayed.add(new BigDecimal(order.getBalanceMoney()));
                    hasPayed = hasPayed.add(new BigDecimal(order.getAlipayMoney()));
                    hasPayed = hasPayed.add(new BigDecimal(order.getWeixinMoney()));
                    hasPayed = hasPayed.add(new BigDecimal(order.getUnionpayMoney()))
                        .setScale(2, BigDecimal.ROUND_HALF_UP);
//                  hasPayed=hasPayed.add(new BigDecimal(order.getThanksCash()!=null?order.getThanksCash():0));
//                  hasPayed=hasPayed.add(new BigDecimal(order.getGoodsCash()!=null?order.getGoodsCash():0));
//                  hasPayed=hasPayed.add(new BigDecimal(order.getProtectPrice()!=null?order.getProtectPrice():0)).setScale(2, BigDecimal.ROUND_HALF_UP);
                }

                BigDecimal money = new BigDecimal(order.getRealPay())
                    .add(new BigDecimal(null != weightPrice ? weightPrice : 0));//还需支付的钱
                money = money.subtract(coupon_hasPayed);
                if (money.doubleValue() < 0) {

                    money = BigDecimal.ZERO;
                }
                money = money.setScale(2, BigDecimal.ROUND_HALF_UP);
//                if(null!=order.getThanksCash() && order.getThanksCash()>0){
//                    money=money.add(new BigDecimal(order.getThanksCash()));
//                  }
//                  if(null!=order.getGoodsCash() && order.getGoodsCash()>0){
//                    money=money.add(new BigDecimal(order.getGoodsCash()));
//                  }
//                  if(null!=order.getProtectPrice() && order.getProtectPrice()>0){
//                      money=money.add(new BigDecimal(order.getProtectPrice()));
//                    }
                money = money.subtract(hasPayed);
                if (money.doubleValue() <= 0) {
                    //直接结算
                    Driver driver = driverService.findOne(order.getEmployId());
                    result = errandService
                        .completeTaskNewV3(order, passenger, driver, "clickComplete", null,
                            hasPayed);

                    if (result.isSuccess()) {
                        OrderEmployHasPayEvent orderEmployHasPayEvent = new OrderEmployHasPayEvent(
                            passenger, order.getId(), "errand");
                        applicationEventMulticaster.multicastEvent(orderEmployHasPayEvent);

                        ResultTransport instance = ResultTransport
                            .getErrorBy(ErrorConstantV4.SUCCESS);
                        instance.setData("hasfinished");
                        return instance;
                    } else {
                        ResultTransport instance = ResultTransport
                            .getErrorBy(ErrorConstantV4.SERVER_ERROR);
                        return instance;
                    }

                } else {
                    //进入确认页面,修改司机在线状态
                    Driver driver = driverService.findOne(order.getEmployId());
                    if (null != driver) {
                        List<OrderUp> activedList = errandService
                            .findActivedOrdersByDriver(driver.getId());
                        if (!CollectionUtils.isEmpty(activedList)) {
                            long pai = 0;
                            long jie = 0;
                            long busy = 0;
                            for (OrderUp activedOrder : activedList) {
                                if (!activedOrder.getId().equals(order.getId())) {
                                    if (activedOrder.getStatus()
                                        .equals(Order.ORDER_STATUS_PAIDAN)) {
                                        ++pai;
                                    } else if (activedOrder.getStatus()
                                        .equals(Order.ORDER_STATUS_JIEDAN)) {
                                        ++jie;
                                    } else if (activedOrder.getStatus()
                                        .equals(Order.ORDER_STATUS_ZHIXING)) {
                                        ++busy;
                                    }
                                }
                            }
                            if (busy > 0 || jie > 0) {
                                driver.setStatus(Driver.DRIVER_BUSY);
                            } else if (pai > 0) {
                                driver.setStatus(Driver.DRIVER_APPLY_ORDER);
                            } else {
                                driver.setStatus(Driver.DRIVER_ONLINE);
                                driver.setJobStatus(null);
                            }
                            driverMapper.updateStatusAndJobStatusByPrimaryKey(driver.getStatus(),
                                driver.getJobStatus(), driver.getId());
                        }
                    }
                    //客户端提醒付费推送
                    ErrandOrderUpConfirmEvent errandOrderConfirmEvent = new ErrandOrderUpConfirmEvent(
                        order);
                    applicationEventMulticaster.multicastEvent(errandOrderConfirmEvent);

                    ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                    instance.setData("waitfinish");
                    return instance;
                }
            } else {
                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
                return instance;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            return instance;
        }

    }

    @RequestMapping(value = "finishTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport finishTask(Long orderId, String payType, String who) {

        logger.error("recv orderId:{},payType{}", orderId, payType);

        if (null == orderId || StringUtils.isBlank(payType)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        if (!"helppay".equals(payType) && !"sign".equals(payType) && !"balance".equals(payType)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        OrderUp order = errandService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (!order.getTreatment()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_CONFIRM);
        }

        Setting setting = settingUtils.get();

        Double afterPayMoney = 0d;
        if (null != order.getPrePayTypeDetail()) {
            if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                afterPayMoney = order.getRealPay() - order.getCouponMoney().doubleValue();
            } else {
                afterPayMoney = order.getRealPay() - order.getShouldPay();
            }
        } else {
            afterPayMoney = order.getRealPay();
        }

        Driver driver = driverService.findOne(order.getEmployId());
        if ("helppay".equals(payType)) {//如果是代付，服务人员收到现金，余额减钱
            if (afterPayMoney.doubleValue() >= 10000) {
                return ResultTransport.getErrorBy(ErrorConstantV4.HELP_PAY_MONEY_TOOLARGE);
            }
            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
            }
            if (!setting.isAllowHelppayNe()) {
                if (driver.getVirtual().doubleValue() < (afterPayMoney.doubleValue())) {
                    return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_MONEY_NOT_ENOUGH);
                }
            }
        }

        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        if (null != passenger) {
            if ("sign".equals(payType)) {//签单支付
                if (passenger.getType() == Passenger.TYPE_PASSENGER) {
                    if (!passenger.isAllowOverdraw()) {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_ALLOW_SIGN);
                    }
                } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
                    Enterprise enterprise = memberService
                        .findOneEnterprise(passenger.getEnterprise_id());
                    if (!enterprise.isAllowOverdraw()) {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_ALLOW_SIGN);
                    }
                }
            } else if ("balance".equals(payType)) {//余额支付
                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    BigDecimal shengyuMoney = BigDecimal.ZERO;
                    shengyuMoney = shengyuMoney.add(passenger.getNodrawMoney());
                    if (passenger.getDrawMoney().doubleValue() > 0) {
                        shengyuMoney = shengyuMoney.add(passenger.getDrawMoney());
                    }
                    if (shengyuMoney.doubleValue() < afterPayMoney) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.PASSENGER_MONEY_NOT_ENOUGH);
                    }
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = memberService
                        .findOneEnterprise(passenger.getEnterprise_id());
                    BigDecimal shengyuMoney = BigDecimal.ZERO;
                    shengyuMoney = shengyuMoney.add(enterprise.getNodrawMoney());
                    if (enterprise.getDrawMoney().doubleValue() > 0) {
                        shengyuMoney = shengyuMoney.add(enterprise.getDrawMoney());
                    }
                    if (shengyuMoney.doubleValue() < afterPayMoney) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.PASSENGER_MONEY_NOT_ENOUGH);
                    }
                }
            }
        }

        try {

            Result<OrderUp> result = errandService
                .completeTaskNewV3(order, passenger, driver, "clickPay", payType, null);

            if (result.isSuccess()) {

                if (StringUtils.isNotBlank(who) && who.equals("passenger")) {
                    OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(
                        driver, order.getId(), "errand");
                    applicationEventMulticaster.multicastEvent(orderPassengerHasPayEvent);
                } else {
                    OrderEmployHasPayEvent orderEmployHasPayEvent = new OrderEmployHasPayEvent(
                        passenger, order.getId(), "errand");
                    applicationEventMulticaster.multicastEvent(orderEmployHasPayEvent);
                }

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                return instance;
            } else {
                if (result.getErrorcode()
                    .equals(String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()))) {
                    ResultTransport instance = ResultTransport
                        .getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED);
                    return instance;
                } else {
                    ResultTransport instance = ResultTransport
                        .getErrorBy(ErrorConstantV4.SERVER_ERROR);
                    return instance;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            return instance;
        }

    }

    @RequestMapping(value = "pushAcceptOrder")
    public @ResponseBody
    ResultTransport pushAcceptOrder(Long employId, Long orderId) {

        if (null == orderId || null == employId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Driver driver = driverService.findOne(employId);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        OrderUp order = errandService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {

            driverService
                .updateStatusAndJobStatus(Driver.DRIVER_BUSY, Driver.DRIVER_JOBSTATUS_PAOTUI,
                    order.getEmployId());

            PaotuiOrderUpAcceptEvent acceptEvent = new PaotuiOrderUpAcceptEvent(order, driver);
            applicationEventMulticaster.multicastEvent(acceptEvent);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(orderId);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "pushRefuseOrder")
    public @ResponseBody
    ResultTransport pushRefuseOrder(Long orderId, Long employId, String content) {

        if (null == orderId || null == employId || StringUtils.isBlank(content)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Driver driver = driverService.findOne(employId);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        OrderUp order = errandService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {

            Long amount = errandService.countBusyAmount(driver.getId());
            if (amount == 0) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService
                        .updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                }
            }

            //拒绝工单记录
            DriverRefuseRecord driverRefuseRecord = new DriverRefuseRecord();
            driverRefuseRecord.setEmployId(driver.getId());
            driverRefuseRecord.setEmployRealName(driver.getRealname());
            driverRefuseRecord.setEmployUserName(driver.getUsername());
            driverRefuseRecord.setEmployPhone(driver.getPhone());
            driverRefuseRecord.setHappend(new Date());
            driverRefuseRecord.setOrderId(order.getId());
            driverRefuseRecord.setOrderNumber(order.getOrderNo());
            driverRefuseRecord.setOrderCompanyId(order.getCompanyId());
            driverRefuseRecord.setMemo(content);
            driverRefuseRecord.setOrderType(DriverRefuseRecord.OrderType.paotui);
            driverRefuseRecordService.save(driverRefuseRecord);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "pushCancelOrder")
    public @ResponseBody
    ResultTransport pushCancelOrder(Long orderId) {

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        OrderUp order = errandService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        Driver driver = driverService.findOne(order.getEmployId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {
            errandService.backMoney(orderId);
            Long amount = errandService.countBusyAmount(driver.getId());
            if (amount == 0) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService
                        .updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                }
            }

            ErrandOrderUpCancelEvent cancelEvent = new ErrandOrderUpCancelEvent(order, driver,
                "driverCancel");
            applicationEventMulticaster.multicastEvent(cancelEvent);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "pushRunOrder")
    public @ResponseBody
    ResultTransport pushRunOrder(Long orderId) {

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        OrderUp order = errandService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        Driver driver = driverService.findOne(order.getEmployId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());

//		if(null==passenger){
//			return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
//		}

        try {

            if (null != passenger) {
                ErrandOrderUpRunEvent runEvent = new ErrandOrderUpRunEvent(order, passenger);
                applicationEventMulticaster.multicastEvent(runEvent);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    //预算费用(areaId,经纬度)
    @RequestMapping(value = "getPriceByAreaId")
    public @ResponseBody
    ResultTransport getPriceByAreaId(
        @RequestParam(required = true, value = "areaId") Long areaId,
        @RequestParam(required = true, value = "startLat") Double startLat,
        @RequestParam(required = true, value = "startLng") Double startLng,
        @RequestParam(required = false, value = "endLat") Double endLat,
        @RequestParam(required = false, value = "endLng") Double endLng) {

        if (null == areaId || null == startLat || null == startLng) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        try {
            Double mileage = 0.0;
            Integer time = 0;
            if (startLat != null && startLng != null && endLat != null && endLng != null) {
                Result<Map<String, Long>> result = HttpClientUtil
                    .getDistanceAndTimeValueByTwoPoints(startLng, startLat, endLng, endLat);
                Map<String, Long> result2 = result.getResult();
                Long distance = result2.get("distance");//米
                Long timemis = result2.get("time");//秒
                time = (int) (timemis / 60);
                mileage = (double) (distance / 1000);
            }
            Map<String, Object> map2 = errandService.getNewPrice(areaId, mileage, time);
            if ((Boolean) map2.get("success")) {
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("money", map2.get("money"));
                data.put("mileage", mileage);
                data.put("time", time);
                data.put("startPrice", map2.get("startPrice"));
                data.put("mileagePrice", map2.get("mileagePrice"));
                data.put("travelTimePrice", map2.get("travelTimePrice"));
                data.put("pay_detail", map2.get("pay_detail"));

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                instance.setData(data);
                return instance;
            } else {
                return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "getPriceByTimeAndMileage")
    public @ResponseBody
    ResultTransport getPriceByTimeAndMileage(
        @RequestParam(required = true, value = "areaId") Long areaId,
        @RequestParam(required = true, value = "time") Integer time,
        @RequestParam(required = true, value = "mileage") Double mileage) {
        if (null == areaId || null == time || null == mileage) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        try {
            Map<String, Object> map2 = errandService.getNewPrice(areaId, mileage, time);
            if ((Boolean) map2.get("success")) {
                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                instance.setData(map2.get("money"));
                return instance;
            } else {
                return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    /**
     * 根据跑腿子类型下单
     */
    @RequestMapping(value = "getErrandType", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport getErrandType(Long errandTypeId) {
        if (null == errandTypeId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        try {
            OrderType orderType = errandService.findByTypeId(errandTypeId);
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(orderType);
            return instance;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    /**
     * 根据公司id查询跑腿子类型
     */
    @RequestMapping(value = {"queryType"}, method = RequestMethod.GET)
    public ResultTransport queryType(
        @RequestParam("companyId") Long companyId,
        @RequestParam("appKey") String appKey) {
        Setting setting = settingUtils.get();
        List<OrderType> orderTypeList = errandService.queryTypeV4(companyId);
        if (null != orderTypeList && orderTypeList.size() > 0) {
            for (int i = 0; i < orderTypeList.size(); i++) {
                orderTypeList.get(i)
                    .setTypepicture(setting.getWebUrl() + orderTypeList.get(i).getTypepicture());
            }
        }
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(orderTypeList);
        return instance;
    }

}
